import logging
import requests
import time
from typing import Optional

class LokiHandler(logging.Handler):
    def __init__(self, url, tags=None, auth=None):
        super().__init__()
        self.url = url
        self.tags = tags or {}
        self.auth = auth

    def emit(self, record):
        try:
            msg = self.format(record)
            timestamp = int(time.time() * 1e9)
            
            labels = {}
            for key, value in self.tags.items():
                labels[key] = str(value)
            
            payload = {
                'streams': [{
                    'stream': labels,
                    'values': [[str(timestamp), msg]]
                }]
            }
            
            # print(f"Loki发送日志到: {self.url}")
            # print(f"发送的数据: {payload}")
            
            response = requests.post(
                self.url, 
                json=payload,
                auth=self.auth,
                verify=False
            )
            # print(f"Loki响应状态码: {response.status_code}")
            # print(f"Loki响应内容: {response.text}")
        except Exception as e:
            print(f"发送日志到Loki时出错: {str(e)}")
            self.handleError(record)

def setup_loki_logger(
    name: str,
    loki_url: str,
    loki_username: Optional[str] = None,
    loki_password: Optional[str] = None,
    tags: dict = None
) -> logging.Logger:
    """
    设置Loki日志记录器
    Args:
        name: 日志记录器名称
        loki_url: Loki服务器URL
        loki_username: Loki用户名（可选）
        loki_password: Loki密码（可选）
        tags: 额外的标签（可选）
    Returns:
        logger: 配置好的Loki日志记录器
    """
    print(f"正在设置Loki日志记录器...")
    print(f"Loki URL: {loki_url}")
    
    # 创建日志记录器
    logger = logging.getLogger(f"{name}_loki")
    logger.setLevel(logging.DEBUG)

    # 默认标签
    default_tags = {
        "application": "padbot",
        "environment": "production"
    }
    if tags:
        default_tags.update(tags)
    
    print(f"使用的标签: {default_tags}")

    # 配置认证信息
    auth = None
    if loki_username and loki_password:
        auth = (loki_username, loki_password)
        print("已配置认证信息")

    # 创建Loki处理器
    try:
        handler = LokiHandler(
            url=loki_url,
            tags=default_tags,
            auth=auth
        )
        print("成功创建Loki处理器")
    except Exception as e:
        print(f"创建Loki处理器时出错: {str(e)}")
        return logger

    # 设置日志格式
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    handler.setFormatter(formatter)

    # 添加处理器到日志记录器
    logger.addHandler(handler)
    print("Loki日志记录器设置完成")

    return logger
